package net.alche.al.util.far.pojo.ext;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimerTask;

import net.alche.al.util.far.pojo.FaTimerAbs;
// 简单的定时器
public class InnerTimerDo extends TimerTask {
  Map<Integer, FaTimerAbs> timerMap = new HashMap<>();

  public InnerTimerDo(Map<Integer, FaTimerAbs> timerMap) {
    this.timerMap = timerMap;
  }

  @Override
  public void run() {
    if (!timerMap.isEmpty()) {
      Date now = new Date();
      for (FaTimerAbs ta : timerMap.values()) {
        if (this.isMatch(ta, now)) {
          ta.lastDone = now;
          try{
            ta.start(now);
          }catch(Exception ex){
            ex.printStackTrace();
          }
        }
      }
    }
  }

  public boolean isMatch(FaTimerAbs ta, Date now) {
    switch (ta.unit) {
      case "sec": {
        if ((now.getTime() - ta.lastDone.getTime()) > ta.timeVal * 1000) {
          return true;
        }
        break;
      }
      case "minute": {
        if ((now.getTime() - ta.lastDone.getTime()) > ta.timeVal * 1000 * 60) {
          return true;
        }
        break;
      }
      case "hour": {
        if ((now.getTime() - ta.lastDone.getTime()) > ta.timeVal * 1000 * 60 * 60) {
          return true;
        }
        break;
      }
    }
    return false;
  }
}